#include <Window.h>
#include "MainWindow.h"
#include <Application.h>
#include <LayoutBuilder.h>
#include <Catalog.h>
#include <File.h>
#include <Directory.h>
#include <Alert.h>
#include <InterfaceDefs.h>
#include <fstream>
#include <string>
#include "ScelConverter.h"

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "MainWindow"

MainWindow::MainWindow()
    : BWindow(BRect(100, 100, 700, 500), "BeCJKZiku", B_TITLED_WINDOW,
              B_ASYNCHRONOUS_CONTROLS | B_QUIT_ON_WINDOW_CLOSE)
{
    _InitInterface();
    fFilePanel = nullptr;
}

MainWindow::~MainWindow()
{
}

bool MainWindow::QuitRequested()
{
    be_app->PostMessage(B_QUIT_REQUESTED);
    return true;
}

void MainWindow::MessageReceived(BMessage *message)
{
    switch (message->what)
    {
    case MSG_GENERATE:
        _GenerateCinFile();
        break;
    case MSG_BROWSE_SCEL:
        _BrowseScelFile();
        break;
    case MSG_CONVERT_SCEL:
        _ConvertScelFile();
        break;
    case B_REFS_RECEIVED:
        {
            entry_ref ref;
            if (message->FindRef("refs", &ref) == B_OK) {
                BPath path(&ref);
                if (path.InitCheck() == B_OK) {
                    fScelPathControl->SetText(path.Path());
                }
            }
        }
        break;
    default:
        BWindow::MessageReceived(message);
        break;
    }
}

void MainWindow::_BrowseScelFile()
{
    if (fFilePanel == nullptr) {
        fFilePanel = new BFilePanel(B_OPEN_PANEL);
        fFilePanel->SetTarget(this);
    }
    fFilePanel->Show();
}

void MainWindow::_ConvertScelFile()
{
    const char* scelPath = fScelPathControl->Text();
    if (strlen(scelPath) == 0) {
        BAlert *alert = new BAlert("错误", "请先选择搜狗词库文件", "确定");
        alert->Go();
        return;
    }

    // 创建转换器实例
    ScelConverter converter;
    ScelConverter::DictInfo dictInfo;

    // 解析scel文件
    if (!converter.ParseScelFile(scelPath, dictInfo)) {
        BAlert *alert = new BAlert("错误", "无法解析搜狗词库文件", "确定");
        alert->Go();
        return;
    }

    // 获取输出路径
    const char* outputPath = fOutputPathControl->Text();
    BPath path(outputPath);
    BPath parent;
    path.GetParent(&parent);

    // 创建输出目录
    create_directory(parent.Path(), 0777);

    // 保存为cin文件
    if (!converter.SaveToCin(outputPath)) {
        BAlert *alert = new BAlert("错误", "保存CIN文件失败", "确定");
        alert->Go();
        return;
    }

    // 显示成功信息
    BString message;
    message.SetToFormat("词库转换完成！\n词库名称：%s\n词库类型：%s\n词条数量：%d",
                       dictInfo.name.String(),
                       dictInfo.type.String(),
                       converter.GetEntries().size());

    BAlert *alert = new BAlert("成功", message.String(), "确定");
    alert->Go();
}

void MainWindow::_InitInterface()
{
    fOutputPathControl = new BTextControl("outputPath", "输出路径：",
                                          "/boot/home/config/non-packaged/data/BeCJK/cin/Simplified Chinese/pinyin.cin",
                                          nullptr);

    fScelPathControl = new BTextControl("scelPath", "搜狗词库路径：",
                                       "",
                                       nullptr);

    fGenerateButton = new BButton("generate", "生成CIN文件",
                                  new BMessage(MSG_GENERATE));

    fBrowseScelButton = new BButton("browseScel", "浏览...",
                                    new BMessage(MSG_BROWSE_SCEL));

    fConvertScelButton = new BButton("convertScel", "转换词库",
                                     new BMessage(MSG_CONVERT_SCEL));

    BLayoutBuilder::Group<>(this, B_VERTICAL)
        .SetInsets(B_USE_DEFAULT_SPACING)
        .Add(fOutputPathControl)
        .AddGroup(B_HORIZONTAL)
            .Add(fScelPathControl)
            .Add(fBrowseScelButton)
        .End()
        .AddGroup(B_HORIZONTAL)
            .Add(fGenerateButton)
            .Add(fConvertScelButton)
        .End()
        .End();
}

void MainWindow::_GenerateCinFile()
{
    BPath path(fOutputPathControl->Text());
    BPath parent;
    path.GetParent(&parent);

    // 创建目录
    create_directory(parent.Path(), 0777);

    // 打开文件
    std::ofstream outFile(path.Path());
    if (!outFile.is_open())
    {
        BAlert *alert = new BAlert("错误", "无法创建输出文件", "确定");
        alert->Go();
        return;
    }

    // 写入cin文件头部
    outFile << "%gen_inp\n"
            << "%ename pinyin\n"
            << "%cname 拼音\n"
            << "%encoding UTF-8\n"
            << "%selkey 1234567890\n"
            << "%keyname begin\n"
            << "%keyname end\n"
            << "%chardef begin\n";

    // TODO: 在这里添加拼音映射数据
    // 示例：
    outFile << "a 啊";
    outFile << "ai 爱";
    outFile << "an 安";

    // 写入cin文件尾部
    outFile << "%chardef end";
    outFile.close();

    BAlert *alert = new BAlert("成功", "CIN文件已生成", "确定");
    alert->Go();
}